package project.messagestack.network.mail;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import project.messagestack.utils.Logger;

public class Message {

  enum msgState {
    SEEN, UNSEEN
  }

  public enum msgType {
    FACEBOOK, TWITTER, MAIL, NK, SMS, BUZZ
  }

  private String mMessageBody, mSender, mSubject;
  private Date mServerRcvDate;
  private msgState mState;
  private msgType mType;

  private final DateFormat dateFormat;
  private final DateFormat dateFormat1;
  private final DateFormat dateFormat2;

  public Message(String rawMessage, msgType mType) {
    dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
    dateFormat1 = new SimpleDateFormat("d MMM yyyy HH:mm:ss Z");
    dateFormat2 = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");

    this.mType = mType;
    parseHeaders(rawMessage);
    parseBody(rawMessage);

  }

  public String getMessageBody() {
    return mMessageBody;
  }

  public String getSender() {
    return mSender;
  }

  public String getSubject() {
    return mSubject;
  }

  public Date getReceiveDate() {
    return mServerRcvDate;
  }

  public long getReceiveTimestamp() {
    return mServerRcvDate.getTime();
  }

  public msgState getFlag() {
    return mState;
  }

  public void readMsg() {
    this.mState = msgState.SEEN;
  }

  public msgType getType() {
    return mType;
  }

  private void parseHeaders(String rawMsg) {
    String headers = rawMsg.substring(0, rawMsg.indexOf("\n\n"));
    String[] hLines = headers.split("\n");
    for (int i = 0; i < hLines.length; i++) {
      if (hLines[i].startsWith("From: ")) {
        mSender = hLines[i].substring(6);
      } else if (hLines[i].startsWith("Date: ")) {
        try {
          mServerRcvDate = dateFormat.parse(hLines[i].substring(6));
        } catch (ParseException e) {
          try {
            mServerRcvDate = dateFormat1.parse(hLines[i].substring(6));
          } catch (Exception e1) {
            try {
              mServerRcvDate = dateFormat2.parse(hLines[i].substring(6));
            } catch (Exception e2) {
              Logger.logError("Error while parse date in message.");
            }

          }
        }

      } else if (hLines[i].startsWith("Subject: ")) {
        mSubject = hLines[i].substring(9);
      } else if (hLines[i].startsWith("Flag: ")) {
        mState = msgState.valueOf(hLines[i].substring(6).toUpperCase());
      }

    }
  }

  private void parseBody(String rawMsg) {
    mMessageBody = rawMsg.substring(rawMsg.indexOf("\n\n") + 2);
  }

}
